package com.emm.yixun.website.listeners;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;
import org.activiti.engine.history.ProcessInstanceHistoryLog;

import com.emm.yixun.basic.service.BusinessAbnormaService;
import com.emm.yixun.basic.service.PayDepositService;
import com.emm.yixun.basic.service.ProjectRoomService;
import com.emm.yixun.basic.service.ProjectSettingService;
import com.emm.yixun.basic.service.SignedService;
import com.emm.yixun.common.enums.ProcessTypeEnums;
import com.emm.yixun.common.model.BusinessAbnorma;
import com.emm.yixun.common.model.PayDeposit;
import com.emm.yixun.common.model.Signed;
import com.emm.yixun.common.model.dto.BusinessAbnormaDto;
import com.emm.yixun.common.model.dto.NoticeEntity;
import com.emm.yixun.common.model.dto.PayDepositDto;
import com.emm.yixun.common.model.dto.ProjectRoomDto;
import com.emm.yixun.common.model.dto.SignedDto;
import com.emm.yixun.common.model.enums.AuditStatusEnum;
import com.emm.yixun.common.model.enums.BusinessTypeEnum;
import com.emm.yixun.common.model.enums.RoomStatusEnum;
import com.emm.yixun.customer.service.impl.app.ActivitiProcessServiceImpl;
import com.emm.yixun.customer.service.impl.app.SpringWebContextUtil;
import com.emm.yixun.system.service.notice.signed.SignedDiscountNoticeFacade;

public class SignedDiscountListeners implements Serializable, ExecutionListener{
	private static final long serialVersionUID = 5304231329519610864L;

	@Override
	public void notify(DelegateExecution execution) throws Exception {
		String id=execution.getProcessBusinessKey();
		String processInstanceId=execution.getProcessInstanceId();
		SignedService signedService=getSignedService();
		Signed signed=signedService.selectById(Long.valueOf(id));
		if(signed == null){
			throw new Exception("签约记录不存在");
		}
		BusinessAbnormaService businessAbnormaService=getBusinessAbnormaService();
		ActivitiProcessServiceImpl activitiProcessService=getActivitiProcessServiceImpl();
		
		//动态获取签约折扣流程KEY
		String startProcessKey_qy = activitiProcessService.getProcessKey(signed.getMerchantId(), signed.getProjectId(), ProcessTypeEnums.PROCESS_KEY_12);
		if(startProcessKey_qy == null){
			throw new Exception("项目未设置签约折扣流程，请去项目流程菜单配置!");
		}
		
		if(activitiProcessService.isCheckPass(processInstanceId)){
			/**
			 * 1.修改签约折扣审核状态为通过   
			 * 2.发起签约审批
			 */
			BusinessAbnormaDto queryDto=new BusinessAbnormaDto();
			queryDto.setBusinessId(signed.getId());
			queryDto.setBusinessType(BusinessTypeEnum.SIGNED.getNo());
			queryDto.setProcInstId(processInstanceId);
			List<BusinessAbnorma> responseList=businessAbnormaService.selectListByDto(queryDto);
			if(null!=responseList && responseList.size()>0){
				BusinessAbnorma businessAbnorma=responseList.get(0);
				BusinessAbnormaDto updateBADto=new BusinessAbnormaDto();
				updateBADto.setId(businessAbnorma.getId());
				updateBADto.setAuditStatus(AuditStatusEnum.SUCCESS.getNo());
				businessAbnormaService.update(updateBADto);
			}
			Map<String, Object> variables = new HashMap<String, Object>();
			ProcessInstanceHistoryLog processInstanceHistoryLog=getHistoryService().createProcessInstanceHistoryLogQuery(processInstanceId).singleResult();
			getIdentityService().setAuthenticatedUserId(processInstanceHistoryLog.getStartUserId());
			String pid=activitiProcessService.startProcessInstance(signed.getMerchantId(), signed.getProjectId(), startProcessKey_qy, signed.getId().toString(), variables);
			SignedDto updateSubscribeDto=new SignedDto();
			updateSubscribeDto.setId(signed.getId());
			updateSubscribeDto.setAuditStatus(AuditStatusEnum.AUDIT.getNo());
			updateSubscribeDto.setProcInstId(pid);
			Integer response=signedService.update(updateSubscribeDto);
			if(response < 1){
				throw new Exception("签约审核状态修改错误");
			}
			
			/**
			 * （签约折扣审核通过）推送消息到app
			 * @author ny
			 * @param param noticeType 提醒类型, noticeBusinessId 业务主键Id
			 * @return 【${auditStatus}】房号：${roomName}；客户：${customer};
			 */
			NoticeEntity noticeEntity = new NoticeEntity();
			noticeEntity.setNoticeBusinessId(signed.getId());
			noticeEntity.setNoticeType("7");
			noticeEntity.setProcessInstanceId(processInstanceId);
			getSignedDiscountNoticeFacade().createSignedDiscountNotice(noticeEntity);
		}else{
			/**
			 * 1.修改认购折扣审核状态为不通过
			 * 2.修改房源状态为未售或者认筹
			 */
			
			BusinessAbnormaDto queryDto=new BusinessAbnormaDto();
			queryDto.setBusinessId(signed.getId());
			queryDto.setBusinessType(BusinessTypeEnum.SIGNED.getNo());
			queryDto.setProcInstId(processInstanceId);
			List<BusinessAbnorma> responseList=businessAbnormaService.selectListByDto(queryDto);
			if(null!=responseList && responseList.size()>0){
				BusinessAbnorma businessAbnorma=responseList.get(0);
				BusinessAbnormaDto updateBADto=new BusinessAbnormaDto();
				updateBADto.setId(businessAbnorma.getId());
				updateBADto.setAuditStatus(AuditStatusEnum.REJECT.getNo());
				Integer businessResponse= businessAbnormaService.update(updateBADto);
				if(businessResponse < 1){
					throw new Exception("签约折扣审核状态修改错误");
				}
			}

			//房源状态为未售或者认筹
			ProjectRoomDto projectRoomDto=new ProjectRoomDto();
			projectRoomDto.setId(signed.getRoomId());
			if(null==signed.getSubscribeId() && null==signed.getPayDepositId()){
				projectRoomDto.setRoomStatus(RoomStatusEnum.VENDIBILITY.getNo());
			}else if(null!=signed.getSubscribeId()){
				projectRoomDto.setRoomStatus(RoomStatusEnum.BUY.getNo());
			}else if(null!=signed.getPayDepositId()){
				PayDepositDto payDepositDto = new PayDepositDto();
				payDepositDto.setM_auditStatus(" and t.audit_status in (1,3)");
				payDepositDto.setRoomId(signed.getRoomId());
				List<PayDeposit> payDepositList = getPayDepositService().selectListByDto(payDepositDto);
				if(payDepositList==null||payDepositList.size()==0){
					projectRoomDto.setRoomStatus(RoomStatusEnum.VENDIBILITY.getNo());
				}else{
					projectRoomDto.setRoomStatus(RoomStatusEnum.RESERVE.getNo());
				}
			}
			getProjectRoomService().update(projectRoomDto);
			
			SignedDto updateSubscribeDto=new SignedDto();
			updateSubscribeDto.setId(signed.getId());
			updateSubscribeDto.setAuditStatus(AuditStatusEnum.REJECT.getNo());
			updateSubscribeDto.setCheckDate(new Date());
			signedService.update(updateSubscribeDto);
			
			/**
			 * （签约折扣审核不通过）推送消息到app
			 * @author ny
			 * @param param noticeType 提醒类型, noticeBusinessId 业务主键Id
			 * @return 【${auditStatus}】房号：${roomName}；客户：${customer};
			 */
			NoticeEntity noticeEntity = new NoticeEntity();
			noticeEntity.setNoticeBusinessId(signed.getId());
			noticeEntity.setNoticeType("7");
			noticeEntity.setProcessInstanceId(processInstanceId);
			getSignedDiscountNoticeFacade().createSignedDiscountNotice(noticeEntity);
		}
		
	}
	
	private PayDepositService getPayDepositService(){
		return (PayDepositService)SpringWebContextUtil.getApplicationContext().getBean("payDepositService");
	}
	
	private SignedDiscountNoticeFacade getSignedDiscountNoticeFacade(){
		return (SignedDiscountNoticeFacade)SpringWebContextUtil.getApplicationContext().getBean("signedDiscountNoticeFacade");
	}
	
	private BusinessAbnormaService getBusinessAbnormaService(){
		return (BusinessAbnormaService)SpringWebContextUtil.getApplicationContext().getBean("businessAbnormaService");
	}
	
	private ProjectRoomService getProjectRoomService(){
		return (ProjectRoomService)SpringWebContextUtil.getApplicationContext().getBean("projectRoomService");
	}
	
	@SuppressWarnings("unused")
	private ProjectSettingService getProjectSettingService(){
		return (ProjectSettingService)SpringWebContextUtil.getApplicationContext().getBean("projectSettingService");
	}
	private SignedService getSignedService(){
		return (SignedService)SpringWebContextUtil.getApplicationContext().getBean("signedService");
	}
	
	private ActivitiProcessServiceImpl getActivitiProcessServiceImpl(){
		return (ActivitiProcessServiceImpl)SpringWebContextUtil.getApplicationContext().getBean("activitiProcessServiceImpl");
	}
	
	private IdentityService getIdentityService(){
		return (IdentityService)SpringWebContextUtil.getApplicationContext().getBean("identityService");
	}
	
	@SuppressWarnings("unused")
	private RuntimeService getRuntimeService(){
		return (RuntimeService)SpringWebContextUtil.getApplicationContext().getBean("runtimeService");
	}
	
	private HistoryService getHistoryService(){
		return (HistoryService)SpringWebContextUtil.getApplicationContext().getBean("historyService");
	}
	
}
